package com.imooc.zxing;

import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;

/**
 * 生成二维码
 * Created by Administrator on 2017/8/14.
 */
public class CreateQRcode {
    public static void main(String[] args) {

        // 二维码的宽高
        int width = 300;
        int height = 300;
        // 二维码内容
        String content = "我是中国人";
        // 二维码图片的格式
        String format = "png";

        // 定义二维码参数
        HashMap hints = new HashMap();
        // 字符编码
        hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
        // 纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 边距
        hints.put(EncodeHintType.MARGIN,2);

        try {

            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,hints);
            // 二维码输出的路径
            Path file = new File("D:/code/img.png").toPath();
            // 将二维码进行输出
            MatrixToImageWriter.writeToPath(bitMatrix,format,file);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
